﻿<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

/**
 * Defines the editing form for the autofeedback question type.
 *
 * @copyright &copy; 2007 Jamie Pratt
 * @author Jamie Pratt me@jamiep.org
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
 * @package questionbank
 * @subpackage questiontypes
 */

require_once($CFG->dirroot.'/question/type/autofeedback/autofeedback.php');
/**
 * autofeedback editing form definition.
 */
class question_edit_autofeedback_form extends question_edit_form {
    /**
     * Add question-type specific form fields.
     *
     * @param MoodleQuickForm $mform the form being built.
     */
    function definition_inner(&$mform) {
        $menu = array(get_string('caseno', 'quiz'), get_string('caseyes', 'quiz'));
        $mform->addElement('select', 'usecase', get_string('casesensitive', 'quiz'), $menu);
        
        $mform->addElement('static', 'penalties', 'Штрафы:');
        $mform->addElement('text', 'missingpenalty', 'Пропущенная лексема', 'maxlength="3" size="10"');
        $mform->addRule('missingpenalty', 'missing', 'required', '0.25', 'server');
		$missing =& $mform->getElement('missingpenalty');
		$missing->setValue('0.25');
        $mform->addElement('text', 'oddpenalty', 'Лишняя', 'maxlength="3" size="10"');
        $mform->addRule('oddpenalty', 'Odd', 'required','1', 'server');
		$excess =& $mform->getElement('oddpenalty');
		$excess->setValue('1');
        $mform->addElement('text', 'misplacedpenalty', 'Неправильно расположенная', 'maxlength="3" size="10"');
        $mform->addRule('misplacedpenalty', 'Missing', 'required', '1', 'server');
		$wrongplace =& $mform->getElement('misplacedpenalty');
		$wrongplace->setValue('1');
        $mform->addElement('text', 'typopenalty', 'Опечатка', 'maxlength="3" size="10"');
        $mform->addRule('typopenalty', 'Missing', 'required', '0.1', 'server');
		$typo =& $mform->getElement('typopenalty');
		$typo->setValue('0.1');
        
        $creategrades = get_grade_options();
        $this->add_per_answer_fields($mform, 'Ответ', $creategrades->gradeoptions);
        $mform->closeHeaderBefore('answersinstruct');
        $mform->registerNoSubmitButton('explode');
        $mform->addElement('submit', 'explode', 'Разбить на лексемы');
        
        $explode = optional_param('explode', '', PARAM_TEXT);
        $answer = optional_param('answer','no answer', PARAM_RAW);
        
        if (!empty($explode)) {
            //echo 'exploding <br>';
            $lexemes = array();
            for ($i = 0; $i<count($answer); $i++) {
                
                //echo $i.'<pre>';
                
                
                $item_r_e = '/([^ \t\(\),;]+)|([\(\),;:])/';
                $item_number = preg_match_all($item_r_e, $answer[$i], $items);
                //print_r($items);
                //echo '</pre>';
                $label = null;
                $done = false;
                foreach ($items[0] as $item) {
                    //echo ' in '.$item.' ';
                    $label = $label.$item.'<br>';
                    //echo $label;
                    $done = true;
                }
                //echo 'done: '.$label;
                if ($done) {
                    $lexemenames = &$mform->getElement("lexemedescriptions[$i]");
                    $lexemenames->setLabel($label);
                }
            }
        }
       
        $creategrades = get_grade_options();
        //$this->add_per_answer_fields($mform, get_string('answerno', 'qtype_shortanswer', '{no}'),
            //    $creategrades->gradeoptions);
           // $mform->addElement('static', 'lexemesdescription',' ', 'Введите лексемы правильного ответа и их название (через пробел). Каждую лексему вводите с новой строки'); 
         //   $mform->addElement('textarea', 'lexemedescriptions', 'Лексемы', 'wrap="virtual" rows="10" cols="80"');
    }

    function get_per_answer_fields(&$mform, $label, $gradeoptions, &$repeatedoptions, &$answersoption) {
        $repeated = array();
        $repeated[] =& $mform->createElement('header', 'answerhdr', $label);
        $repeated[] =& $mform->createElement('text', 'answer', get_string('answer', 'quiz'), array('size' => 80));

        $repeated[] =& $mform->createElement('select', 'fraction', get_string('grade'), $gradeoptions);
        $repeated[] =& $mform->createElement('editor', 'feedback', get_string('feedback', 'quiz'),
                                array('rows' => 5), $this->editoroptions);
        $repeated[] =& $mform->createElement('textarea', 'lexemedescriptions', 'Лексемы', 'wrap="virtual" rows="10" cols="80"');
        $repeatedoptions['answer']['type'] = PARAM_RAW;
        $repeatedoptions['fraction']['default'] = 0;
        $answersoption = 'answers';
        return $repeated;
    }
    
    function data_preprocessing($question) {
        //echo '<pre>';
        //$lexemestext = $this->_form->_submitValues['lexemedescriptions'];
        //$lexemeslines = explode('\n', $lexemestext);
        //foreach ($lexemeslines as $lexemeline) {
            
        //}
        function get_rule_name() {
        //return $this->_form->_submitValues['rulename'];
        }
        ////print_r($this);
        //echo '</pre>';
        if (isset($question->options)){
            $answers = $question->options->answers;
            $answers_ids = array();
            if (count($answers)) {
                $key = 0;
                foreach ($answers as $answer){
                    $answers_ids[] = $answer->id;
                    $default_values['answer['.$key.']'] = $answer->answer;
                    $default_values['fraction['.$key.']'] = $answer->fraction;
                    $default_values['feedback['.$key.']'] = array();

                    // prepare feedback editor to display files in draft area
                    $draftid_editor = file_get_submitted_draft_itemid('feedback['.$key.']');
                    $default_values['feedback['.$key.']']['text'] = file_prepare_draft_area(
                        $draftid_editor,       // draftid
                        $this->context->id,    // context
                        'question',   // component
                        'answerfeedback',             // filarea
                        !empty($answer->id)?(int)$answer->id:null, // itemid
                        $this->fileoptions,    // options
                        $answer->feedback      // text
                    );
                    $default_values['feedback['.$key.']']['itemid'] = $draftid_editor;
                    // prepare files code block ends

                    $default_values['feedback['.$key.']']['format'] = $answer->feedbackformat;
                    $key++;
                }
            }
            $default_values['usecase'] = $question->options->usecase;
            $question = (object)((array)$question + $default_values);
        }
        return $question;
    }
    function validation($data, $files) {
        $errors = parent::validation($data, $files);
        //$answers = $data['answer'];
        $answercount = 1;
        $maxgrade = true;
        /* foreach ($answers as $key => $answer) {
            $trimmedanswer = trim($answer);
            if ($trimmedanswer !== ''){
                $answercount++;
                if ($data['fraction'][$key] == 1) {
                    $maxgrade = true;
                }
            } else if ($data['fraction'][$key] != 0 || !html_is_blank($data['feedback'][$key]['text'])) {
                $errors["answer[$key]"] = get_string('answermustbegiven', 'qtype_autofeedback');
                $answercount++;
            }
        } */
        if ($answercount==0){
            $errors['answer[0]'] = get_string('notenoughanswers', 'quiz', 1);
        }
        if ($maxgrade == false) {
            $errors['fraction[0]'] = get_string('fractionsnomax', 'question');
        }
        return $errors;
    }
    function qtype() {
        return 'autofeedback';
    }
}
